package com.szewec.ps.myview.album;

import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.szewec.ps.R;
import com.szewec.ps.base.Constants;
import com.szewec.ps.greenDao.dao.AlbumFile;

import java.io.File;
import java.util.List;

import io.github.luizgrp.sectionedrecyclerviewadapter.Section;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionParameters;

public class AlbumSection extends Section {

    private boolean isEdit = false;
    private final String title;
    private List<AlbumFile> list;
    private ItemClickListener itemClickListener;

    private final RequestOptions mOptions = new RequestOptions()
            .centerCrop()
            .dontAnimate()//图片在占位图的同时下载并实时显示图片,关闭动画
            .format(DecodeFormat.PREFER_RGB_565)
            .placeholder(R.mipmap.icon_image_default)
            .error(R.mipmap.icon_image_error);

    public AlbumSection(@NonNull final String title, @NonNull final List<AlbumFile> list,
                        @NonNull final ItemClickListener itemClickListener,boolean isEdit) {
        super(SectionParameters.builder()
                .itemResourceId(R.layout.section_item)
                .headerResourceId(R.layout.section_header)
                .footerResourceId(R.layout.section_footer)
                .build());

        this.title = title;
        this.list = list;
        this.itemClickListener = itemClickListener;
        this.isEdit = isEdit;
    }

    @Override
    public int getContentItemsTotal() {
        return list.size();
    }

    @Override
    public RecyclerView.ViewHolder getItemViewHolder(View view) {
        return new AlbumItemViewHolder(view);
    }

    @Override
    public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
        final AlbumItemViewHolder itemHolder = (AlbumItemViewHolder) holder;
        final AlbumFile albumFile = list.get(position);
        bindViewHolder(itemHolder, albumFile);

        //添加事件
        itemHolder.getRootView().setOnClickListener(v ->
                itemClickListener.onItemViewClicked(title, itemHolder.getAdapterPosition(), albumFile)
        );
        //添加事件
        itemHolder.getmImageDelete().setOnClickListener(v ->
                itemClickListener.onItemDeleteClicked(title, itemHolder.getAdapterPosition())
        );
        //编辑事件
        if (itemHolder.getEtdescripyion().getTag() instanceof TextWatcher){
            itemHolder.getEtdescripyion().removeTextChangedListener((TextWatcher)itemHolder.getEtdescripyion().getTag());
        }
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void afterTextChanged(Editable editable) {
                albumFile.setDescription(editable.toString());
            }
        };
        itemHolder.getEtdescripyion().setText(albumFile.getDescription());
        itemHolder.getEtdescripyion().addTextChangedListener(textWatcher);
        itemHolder.getEtdescripyion().setTag(textWatcher);
    }

    @Override
    public RecyclerView.ViewHolder getHeaderViewHolder(final View view) {
        if(hasHeader()){
            return new AlbumHeaderViewHolder(view);
        }
        return null;
    }

    @Override
    public RecyclerView.ViewHolder getFooterViewHolder(View view) {
        if (hasFooter()){
            return new AlbumFooterViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindHeaderViewHolder(final RecyclerView.ViewHolder holder) {
        final AlbumHeaderViewHolder headerHolder = (AlbumHeaderViewHolder) holder;
        headerHolder.tvTitle.setText(Html.fromHtml(title));
    }

    /**
     * 绑定数据（图片、视频）
     *
     * @param itemHolder
     * @param albumFile
     */
    private void bindViewHolder(AlbumItemViewHolder itemHolder, AlbumFile albumFile) {
        if(albumFile.isAdd()){
            //如果是增加按钮，直接显示背景图片
            itemHolder.setAdd(true);
            itemHolder.getmImageDelete().setVisibility(View.GONE);
            itemHolder.getEtdescripyion().setVisibility(View.GONE);
            itemHolder.getPlayConstraintLayout().setVisibility(View.GONE);
            itemHolder.mImageView.setImageResource(R.drawable.add_file);
        }else{
            String imagePath = albumFile.getPath();//图路径
            itemHolder.setEdit(isEdit());
            //这里设置是否是视频只是为了显示播放图片,录音也需要显示播放图片
            itemHolder.setVideo(albumFile.getType() == Constants.FileType.VIDEO || albumFile.getType() == Constants.FileType.RECORD_SOUND);
            if (isEdit){
                itemHolder.etdescripyion.setEnabled(true);
                itemHolder.etdescripyion.setHint("添加描述...");
                //尝试获得焦点
                itemHolder.etdescripyion.requestFocus();
            }else {
                itemHolder.etdescripyion.setEnabled(false);
                itemHolder.etdescripyion.setHint("");
            }
            try {
                if (albumFile.getType() == Constants.FileType.RECORD_SOUND){//如果录音用本地图片
                    itemHolder.mImageView.setImageResource(R.drawable.record_sound);
                }else {
                    if (imagePath.contains("http")){
                        Glide.with(itemHolder.getRootView().getContext()).load(imagePath).into(itemHolder.mImageView);
                    }else {
                        // 加载本地图片
                        File file = new File(imagePath);
                        Glide.with(itemHolder.getRootView().getContext()).load(file).apply(mOptions).into(itemHolder.mImageView);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public boolean isEdit() {
        return isEdit;
    }

    public void setEdit(boolean edit) {
        isEdit = edit;
    }

    public List<AlbumFile> getList() {
        return list;
    }

    public void setList(List<AlbumFile> list) {
        this.list = list;
    }

    public interface ItemClickListener {
        void onItemViewClicked(@NonNull final String sectionTitle, final int itemAdapterPosition, AlbumFile albumFile);

        void onItemDeleteClicked(@NonNull final String sectionTitle, final int itemAdapterPosition);
    }
}
